package com.ruoyi.lxs.common.filter;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class AuthInterceptor implements HandlerInterceptor {


    private static final String SECRET_KEY = "123123123";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorizationHeader = request.getHeader("Authorization");

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去除 "Bearer " 前缀

            try {
                Jws<Claims> claimsJws = Jwts.parser()
                        .setSigningKey(SECRET_KEY)
                        .parseClaimsJws(token);
                return true; // 验证通过，允许请求继续处理
            }catch (ExpiredJwtException e){
                // Token无效或过期
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;

            }catch (UnsupportedJwtException e){
                // 不支持的Token类型
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;

            }catch (MalformedJwtException e){
                // Token格式错误
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;

            }catch (SignatureException e){
                // Token签名错误
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }catch (Exception e) {
                // Token有其他未知问题
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }
        // 请求未携带Token
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}
